/**
 * 实现多个空间主备容灾，需要使用扩展数据库 + 扩展存储
 * 使用方法
 * 在 App.vue 的 onLaunch 函数的第一行添加代码 multiCloud(options); 即可
<script>
	import multiCloud from "@/multi-cloud.js"
	export default {
		onLaunch: function(options) {
			multiCloud.init({
				options,
				cloudConfigUrl: "" // 云端配置在扩展存储中的url访问地址，请修改成你自己的配置文件访问地址
			});
		}
	}
</script>
 */

class multiCloud {
	constructor() {
		this.originalUniCloud = null;
		this.keyName = "multi-cloud-config-temp";
		this.cloudConfigUrl = "";
	}
	/**
	 * 初始化
	 */
	init({ options = {}, cloudConfigUrl }) {
		const { path, query = {} } = options;
		const tempData = uni.getStorageSync(this.keyName);
		this.originalUniCloud = Object.assign({}, uniCloud);
		this.cloudConfigUrl = cloudConfigUrl;
		if (tempData) {
			Object.assign(uniCloud, uniCloud.init(tempData));
		}
		uni.request({
			url: cloudConfigUrl,
			method: "GET",
			header: {
				'Cache-Control': 'no-cache'
			},
			success: (res) => {
				if (res.statusCode === 200 && typeof res.data === "object" && res.data.use) {
					const useName = res.data.use === "main" ? "主空间" : "备用空间";
					console.log(`当前环境：${useName}`);
					const initUniCloud = () => {
						const initData = res.data[res.data.use] || {};
						if (JSON.stringify(tempData) !== JSON.stringify(initData)) {
							if (res.data.use === "main" && !initData.provider) {
								Object.assign(uniCloud, this.originalUniCloud);
							} else {
								Object.assign(uniCloud, uniCloud.init(initData));
							}
							const queryToUrlString = (query) => {
								if (!query || typeof query !== 'object') {
									return '';
								}
								return Object.keys(query).map(key => {
									const value = query[key];
									return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
								}).join('&');
							}
							const urlString = queryToUrlString(query);
							let url = `/${path}`;
							if (urlString) {
								url += `?${urlString}`
							}
							uni.reLaunch({
								url
							});
							uni.setStorageSync(this.keyName, initData);
						}
					}
					if (res.data.use === "main") {
						if (tempData) {
							initUniCloud();
						}
						uni.removeStorageSync(this.keyName);
					} else {
						initUniCloud();
					}
				} else {
					console.error("err", res);
				}
			},
			fail: (err) => {
				console.error("err", err);
			}
		})
	}
	/**
	 * 强制刷新环境
	 */
	forceRefresh() {
		const { cloudConfigUrl } = this;
		uni.request({
			url: `${cloudConfigUrl}?t=${Date.now()}`,
			method: "GET",
			header: {
				'Cache-Control': 'no-cache'
			},
			success: (res) => {
				if (res.statusCode === 200 && typeof res.data === "object" && res.data.use) {
					const useName = res.data.use === "main" ? "主空间" : "备用空间";
					console.log(`当前环境：${useName}`);
					const initData = res.data[res.data.use] || {};
					if (res.data.use === "main" && !initData.provider) {
						Object.assign(uniCloud, this.originalUniCloud);
					} else {
						Object.assign(uniCloud, uniCloud.init(initData));
					}
				} else {
					console.error("err", res);
				}
			},
			fail: (err) => {
				console.error("err", err);
			}
		})
	}
}

export default new multiCloud();